<template>
  <div class="app-container">
    <!--查询参数列-->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="受检企业" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入受检企业"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="受检商品" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入受检商品"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="采样时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="采样类型" prop="sampleType" v-if="advanced">
        <el-select
          v-model="queryParams.sampleType"
          placeholder="请选择采样类型"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="dict in sampleTypeSelect"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="信用代码" prop="uniformCode" v-if="advanced">
        <el-input
          v-model="queryParams.uniformCode"
          placeholder="请输入信用代码"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <a @click="toggleAdvanced" style="margin-left: 8px">
          {{ advanced ? '收起' : '展开' }}
          <i v-if="!advanced" class="el-icon-arrow-down"></i>
          <i v-if="advanced" class="el-icon-arrow-up"></i>
        </a>
      </el-form-item>
    </el-form>
    <!--表格顶部操作栏-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          :disabled="single === true || enter === false"
          @click="handleEnter"
          v-hasPermi="['detection:enter:add']"
        >录入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['detection:enter:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据-->
    <el-table v-loading="loading" :data="unEnterList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="采样编号" align="center" prop="sampleNo" :show-overflow-tooltip="true" width="200"/>
      <el-table-column label="受检企业" align="center" prop="companyName" :show-overflow-tooltip="true" width="120" />
      <el-table-column label="受检企业信用代码" align="center" prop="uniformCode" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="受检商品" align="center" prop="goodsName" width="120" />
      <el-table-column label="检测项目" align="center" prop="itemName" :show-overflow-tooltip="true" width="240" />
      <el-table-column label="采样人" align="center" prop="sampler" width="120" />
      <el-table-column label="采样类型" align="center" prop="sampleType" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.sampleType === 'self' ">企业自检</span>
          <span v-if="scope.row.sampleType === 'task' ">任务检测</span>
          <span v-if="scope.row.sampleType === 'deliver' ">现场送检</span>
        </template>
      </el-table-column>
      <el-table-column label="采样时间" align="center" prop="sampleTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.sampleTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检测状态" align="center" prop="status" width="120">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.status === 1 ">已检测</el-tag>
          <el-tag type="danger" v-if="scope.row.status === 0 ">未检测</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="采样机构" align="center" prop="sampleOrgName" width="150" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleDetail(scope.row)"
            v-hasPermi="['detection:enter:edit']"
          >详情</el-button>

        </template>
      </el-table-column>
    </el-table>

    <!-- 底部分页-->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="采样编号" prop="sampleNo">
              <el-input :disabled="true" v-model="form.sampleNo" placeholder="请输入采样编号" style="width: 240px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测时间" prop="sampleNo">
              <el-date-picker
                v-model="form.checkTime"
                type="datetime"
                style="width: 240px"
                placeholder="选择检测时间时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="采样企业" prop="companyId">
              <el-select :disabled="true" v-model="form.companyId" placeholder="请选择采样企业" style="width: 240px">
                <el-option
                  v-for="dict in companyList"
                  :key="dict.companyId"
                  :label="dict.companyName"
                  :value="dict.companyId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="信用代码" prop="uniformCode">
              <el-input :disabled="true" v-model="form.uniformCode" placeholder="请先选择受检企业"  style="width: 240px"/>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="12">
            <el-form-item label="采样商品" prop="goodsId" >
              <el-select
                :disabled="true"
                v-model="form.goodsId"
                filterable
                remote
                reserve-keyword
                placeholder="请输入商品"
                style="width: 240px"
              >
                <el-option
                  v-for="item in this.goodsList"
                  :key="item.goodsId"
                  :label="item.goodsName"
                  :value="item.goodsId">
                  <span style="float: left">{{ item.goodsName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.ancestorsName }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测项目" prop="itemIds">
              <el-select
                :disabled="true"
                v-model="form.itemIds"
                multiple
                filterable
                placeholder="请选择检测项目"
                style="width: 240px"
              >
                <el-option
                  v-for="item in this.itemList"
                  :key="item.itemId"
                  :label="item.itemName"
                  :value="item.itemId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="检测人" prop="checker">
              <el-input v-model="form.checker" placeholder="请填写检测人"  style="width: 240px"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测编号" prop="checkBatchNo">
              <el-input v-model="form.checkBatchNo" placeholder="请填写检测编号号"  style="width: 240px"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="检测方法" prop="checkMethod">
              <el-select v-model="form.checkMethod" placeholder="请选择检测方法" clearable style="width: 240px">
                <el-option
                  v-for="dict in checkMethodSelect"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测类型" prop="checkMethod">
              <el-select v-model="form.checkType" placeholder="请选择检测类型" clearable style="width: 240px">
                <el-option
                  v-for="dict in checkTypeSelect"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="检测机构" prop="checkOrgId">
              <el-select v-model="form.checkOrgId" placeholder="请选择检测机构" clearable filterable @change="handleCheckOrgSelect" style="width: 240px">
                <el-option
                  v-for="dict in checkOrgList"
                  :key="dict.id"
                  :label="dict.checkOrgName"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机构编码" prop="checkOrgCode">
              <el-input v-model="form.checkOrgCode" placeholder="请先选择受检企业"  style="width: 240px"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-form-item label="检测结果" prop="result">
            <el-radio-group :disabled="true" v-model="form.result">
              <el-radio
                v-for="dict in resultList"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>

        <el-row v-for="(dict,index) in form.itemList" :key="dict.id">
          <el-col :span=12>
            <el-form-item :label="'项目'+(index+1)" :prop="'itemList.' + index + '.itemName'" :rules="{required: true, message: '检测项目不能为空', trigger: 'blur'}">
              <el-input :disabled="true" v-model="dict.itemName" style="width: 240px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测结果" :prop="'itemList.' + index + '.result'" :rules="{required: true, message: '检测结果不能为空', trigger: 'blur'}">
              <el-select v-model="dict.result" placeholder="请选择检测结果" style="width: 240px" @change="handleResult">
                <el-option
                  v-for="dict in resultList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.checkRemark" type="textarea" placeholder="请输入采样备注"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getSample, listSample} from "@/api/detection/sample/sample";
import {listGoods} from "@/api/goods/goods";
import {listCompany} from "@/api/subject/company/company";
import {listItem} from "@/api/item/item";
import {parseDateTime} from "@/utils/moss";
import {check, randomCheckBatchNo} from "@/api/detection/enter/enter";
import {listCheckOrg} from "@/api/subject/checkOrg/checkOrg";

export default {
  name: "index",
  data(){
    return {
      showSearch: true,
      advanced: true,
      loading: false,
      total: 0,
      ids: [],
      //表格选中行数据
      selectRows: [],
      title: '',
      open: false,
      detail: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 已录入禁用
      enter: true,
      // 日期范围
      dateRange: [],
      companyList:[],
      samplerList:[],
      itemList:[],
      goodsList:[],
      checkOrgList: [],
      sampleOrgList:[],
      // 未录入检测的记录
      unEnterList:[],
      form: {},
      checkMethodSelect: [
        {
          label: "酶抑制法",
          value: 1,
        },
        {
          label: "分光光度计",
          value: 2,
        },
        {
          label: "化学比色法",
          value: 3,
        },
        {
          label: "胶体金免疫法",
          value: 4,
        }
      ],
      checkTypeSelect: [
        {
          label: "定性",
          value: 1,
        },
        {
          label: "定量",
          value: 2,
        }
      ],
      resultList: [
        {
          label: "阴性（合格）",
          value: 1
        },
        {
          label: "阳性（不合格）",
          value: 2
        }
      ],
      sampleTypeSelect: [
        {
          label: "企业自检",
          value: "self"
        },
        {
          label: "现场送检",
          value: "deliver"
        },
        {
          label: "任务检测",
          value: "task"
        }
      ],
      queryParams: {
        companyName: undefined,
        uniformCode: undefined,
        status: 1,
        goodsName: undefined,
        sampleType: undefined,
        pageNum: 1,
        pageSize: 10
      },
      rules:{
        sampleNo: [
          { required: true, message: "采样编号不能为空", trigger: "blur" }
        ],
        checkTime: [
          { required: true, message: "检测时间不能为空", trigger: "blur" }
        ],
        companyId: [
          { required: true, message: "受检企业不能为空", trigger: "blur" }
        ],
        uniformCode: [
          { required: true, message: "受检企业信用代码不能为空", trigger: "blur" }
        ],
        goodsId: [
          { required: true, message: "采样商品不能为空", trigger: "blur" }
        ],
        itemIds: [
          { required: true, message: "检测项目不能为空", trigger: "blur" }
        ],
        checker: [
          { required: true, message: "检测人不能为空", trigger: "blur" }
        ],
        checkBatchNo: [
          { required: true, message: "检测编号不能为空", trigger: "blur" }
        ],
        checkMethod: [
          { required: true, message: "检测方法不能为空", trigger: "blur" }
        ],
        checkType: [
          { required: true, message: "检测类型不能为空", trigger: "blur" }
        ],
        checkOrgId: [
          { required: true, message: "检测机构不能为空", trigger: "blur" }
        ],
        checkOrgCode: [
          { required: true, message: "检测结构编码不能为空", trigger: "blur" }
        ],
        result: [
          { required: true, message: "检测结果不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.initSelectTime();
    this.getList();
  },
  methods: {
    //未录入列表
    getList(){
      this.queryParams.status = 0;
      listSample(this.buildQueryTime(this.queryParams, this.dateRange)).then(res => {
        this.unEnterList = res.data;
        this.total = res.total;
      })
    },
    initSelectTime(){
      const end = new Date();
      end.setHours(23,59,59);
      this.dateRange[1] = end;

      const start = new Date();
      start.setDate(start.getDate() - 6);
      start.setHours(0,0,0);
      this.dateRange[0] = start
    },
    handleResult(){
      let handleResult = 1;
      this.form.itemList.forEach(o => {
        if (o.result === 2){
          handleResult = 2;
        }
      })
      this.$set(this.form, 'result', handleResult);
    },
    handleCheckOrgSelect(value){
      const checkOrg = this.checkOrgList.find(opt => opt.id === value);
      this.form.checkOrgCode = checkOrg.checkOrgCode
      this.form.checkOrgName = checkOrg.checkOrgName
    },
    reset(){
      this.form = {
        sampleId: undefined,
        companyName: undefined,
        uniformCode: undefined,
        sampleType: "",
        sampleNo: "",
        sampler:"",
        samplerSign: "",
        sampleTime: parseDateTime(new Date()),
        goodsId: undefined,
        goodsName: undefined,
        itemIds: [],
        itemList: [],
        sampleOrgId: undefined,
        sampleOrgCode: "",
        sampleOrgName: "",
        remark:"",
        deliver: {
          deliverType:"",
          deliverPeople:"",
          deliverPhone:"",
          origin: ""
        },
        checkTime: parseDateTime(new Date()),
        checker: "",
        checkMethod: undefined,
        checkType: undefined,
        checkOrgId: undefined,
        checkOrgName: "",
        checkOrgCode: "",
        checkRemark: ""
      };
      this.resetForm("form");
    },
    //检测录入
    handleEnter(row){
      this.reset();
      listCompany().then(res =>{
        this.companyList = res.data;
      });
      listItem().then(res => {
        this.itemList = res.data;
      })
      listCheckOrg().then(res => {
        this.checkOrgList = res.data;
      })

      //录入检测时，等检测编号生成后再调用详情
      let checkBatchNo
       randomCheckBatchNo().then(res => {
         const sampleId = row.sampleId || this.ids;
         const type = this.selectRows[0].sampleType;
         getSample(type,sampleId).then(res => {
           res.data.checkBatchNo = checkBatchNo
           this.form = res.data;
           this.form.itemIds = this.form.itemId.split(",").map(Number);
           const goods = {"goodsName":this.form.goodsName};
           listGoods(goods).then(res => {
             this.goodsList = res.data
           })
           this.open = true;
           this.title = '检测录入';
           this.form.checkTime = parseDateTime(new Date())
         });
        checkBatchNo = res.data
      })

    },
    handleQuery(){
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.queryParams.status = 1;
      this.getList();
    },
    resetQuery(){
      this.queryParams = {
        pageNum: 1,
        pageSize: 10
      }
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    handleExport(){

    },
    handleDetail(row){

    },

    submitForm(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          const checkForm = {
            sampleId: this.form.sampleId,
            sampleNo: this.form.sampleNo,
            companyId: this.form.companyId,
            uniformCode: this.form.uniformCode,
            companyName: this.form.companyName,
            goodsId: this.form.goodsId,
            goodsName: this.form.goodsName,
            itemId: this.form.itemList.map(o => o.itemId).join(","),
            itemName:  this.form.itemList.map(o => o.itemName).join(","),
            checker: this.form.checker,
            checkBatchNo: this.form.checkBatchNo,
            checkMethod: this.form.checkMethod,
            checkType: this.form.checkType,
            checkOrgId: this.form.checkOrgId,
            checkOrgName: this.form.checkOrgName,
            checkOrgCode: this.form.checkOrgCode,
            checkTime: this.form.checkTime,
            result: this.form.result,
            remark: this.form.checkRemark,
            itemList: this.form.itemList
          }
          check(checkForm).then(res => {
            this.$modal.msgSuccess("录入成功");
            this.open = false;
            this.getList();
          })
        }
      });
    },
    cancel(){
      this.open = false;
      this.reset();
    },
    handleSelectionChange(selection) {
      this.selectRows = selection
      this.ids = selection.map(item => item.sampleId)
      this.enter = !selection.some(item => item.status === 1);
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
  }
}
</script>

<style scoped>

</style>
